package com.app.xinfadi.util;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Response;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.app.xinfadi.BuildConfig;
import com.app.xinfadi.R;
import com.app.xinfadi.base.Constant;
import com.app.xinfadi.base.MyApplication;
import com.app.xinfadi.dao_bean.version.VersionUpdateList;
import com.app.xinfadi.dao.VersionUpdateDao;
import com.app.xinfadi.widget.dialog.DownDialog;
import com.app.xinfadi.widget.dialog.VersionUpdateDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;



public class VersionUpdateUtil {
    private static final String TAG = "VerisonUpdateUtil";
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    // 下载包安装本地存放路径
    // private static final String savePath ="/sdcard/JXKSchool/";
    private static final String savePath = getVideoUpdateDirPath();
    private static final String saveFileName = getVideoUpdateDirPath() + "ElderlyEscort.apk";
    // 服务器返回的apk安装包下载路径
    private static String downloadUrl = "";
    private Context context;
    private Dialog noticeDialog;
    private ProgressBar mProgress;
    private TextView versionUpdatePrecentTv;
    private boolean interceptFlag = false;
    private Dialog downloadDialog;
    private int progress;
    private String localversion;// 本地版本号
    private String version;// 服务器版本号
    private String content; // 更新内容
    private String updateUri;
    private int type;
    public boolean isUpdateVersionDialogShow = false;
    /**
     * 更新UI的Handler
     */
//    @SuppressLint("HandlerLeak")
//    private Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case DOWN_UPDATE:
//                    mProgress.setProgress(progress);
//                    versionUpdatePrecentTv.setText(progress + "%");
//                    break;
//                case DOWN_OVER:
//                    if (downloadDialog != null)
//                        downloadDialog.dismiss();
//                    installApk();
//                    break;
//                default:
//                    break;
//            }
//        }
//
//        ;
//    };
    private AlertDialog dialog;
    private DownDialog.DownDialogHandler mhandler;
    /**
     * 安装包下载线程
     */
    private Runnable downApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(downloadUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                // File file2 = new
                // File(Environment.getExternalStorageDirectory(),
                // "updata.apk");
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    Message msg = Message.obtain();
                    msg.what = DOWN_UPDATE;
                    msg.arg1 = progress;
                    mhandler.sendMessage(msg);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        mhandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 点击取消就停止下载.
                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    private Thread downLoadThread;
    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;

    /**
     * @param context
     * @param type    type <br/>
     *                0,进入初始界面 检测更新 <br/>
     *                1,点击设置 检测更新
     */
    public VersionUpdateUtil(Context context, int type) {
        this.context = context;
        this.type = type;
        localversion = AppUtils.getVersionName(context);
        bas_in = new BounceTopEnter();
        bas_out = new SlideBottomExit();
    }

    /**
     * 获取更新存储路径
     *
     * @return
     */
    public static String getVideoUpdateDirPath() {
        String dirString = Constant.UPDATE_SAVE_PATH;
        File filePath = new File(dirString);
        if (!filePath.exists()) {
            // 如果无法创建
            if (!filePath.mkdirs()) {
                // ToastEcho.makeText(context, "无法创建", ToastEcho.LENGTH_LONG)
                // .show();
            }
        }
        return dirString;
    }

    /**
     * 检查当前版本是否需要更新
     *
     * @return
     */
    public void isNeedUpdate() {
        UpdateVersion();// 获取版本号和uri地址
    }

    private void UpdateVersion() {
        if (BuildConfig.AUTO_UPDATES) {
            VersionUpdateDao versionUpdateDao = new VersionUpdateDao();
            versionUpdateDao.updateVersion(new Response.Listener<VersionUpdateList>() {

                @Override
                public void onResponse(VersionUpdateList versionUpdateList) {
                    if (versionUpdateList.success) {
                        version = versionUpdateList.version_update.version;
                        updateUri = versionUpdateList.version_update.update_uri;
                        downloadUrl = Constant.URL + updateUri;
                        content = versionUpdateList.version_update.content;
                        testVersion(version);
                    }
                }
            });
        }
    }

    /**
     * 检查是否是最新
     *
     * @param version
     * @return
     */
    private boolean testVersion(String version) {
        if (localversion.equals(version)) {
            if (type == 0) {

            } else if (type == 1) {
                Toast.makeText(context, "已经是最新版", Toast.LENGTH_SHORT).show();
            }
            return false;
        } else {
//            showNoticeDialog1();
//            materialDialogDefault();
            versionUpdateDialog();
            return true;
        }
    }

    /**
     * 弹出更新提示对话框
     */
    @Deprecated
    private void showNoticeDialog() {
        Builder builder = new Builder(context);
        builder.setTitle("软件版本更新");
        builder.setMessage("发现新版本！");
        builder.setPositiveButton("下载", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("以后再说", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
        // 设置弹出对话框大小属性
        WindowManager.LayoutParams lp = noticeDialog.getWindow().getAttributes();
        lp.width = 400;
        lp.height = 500;
        noticeDialog.getWindow().setAttributes(lp);
    }

    private void showNoticeDialog1() {
        isUpdateVersionDialogShow = true;
        Builder builder = new Builder(context);
        View contentView = View.inflate(context, R.layout.update_version, null);
        TextView noUpdateBtn = (TextView) contentView.findViewById(R.id.noUpdateBtn);
        TextView updateBtn = (TextView) contentView.findViewById(R.id.updateBtn);
        TextView contentTv = (TextView) contentView.findViewById(R.id.contentTv);
        contentTv.setText(content);
        noUpdateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取消对话框
                isUpdateVersionDialogShow = false;
                dialog.dismiss();
            }
        });

        updateBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                interceptFlag = false;
                showDownloadDialog();
            }
        });
        dialog = builder.create();
        dialog.setView(contentView, 0, 0, 0, 0);
        dialog.show();
        WindowManager.LayoutParams params =
                dialog.getWindow().getAttributes();
        params.width = (int) (MyApplication.getInstance().screenWidth);
        params.height = (int) (MyApplication.getInstance().screenHeight);
        dialog.getWindow().setAttributes(params);
    }

    private void versionUpdateDialog() {
        final VersionUpdateDialog versionUpdateDialog = new VersionUpdateDialog(context);
        versionUpdateDialog.setContent(content)
                .setTitle("软件版本更新")
                .btnText("取消", "确定")
                .setOnBtnClick(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        // 取消对话框
                        isUpdateVersionDialogShow = false;
                        versionUpdateDialog.dismiss();
                    }
                }, new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        interceptFlag = false;
//                        showDownloadDialog();
                        downDialog();

                    }
                })
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();
    }

    private void materialDialogDefault() {
        final MaterialDialog dialog = new MaterialDialog(context);
        dialog.title("软件版本更新")
                .content(content)//
                .btnText("取消", "确定")//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();

        dialog.setOnBtnClickL(
                new OnBtnClickL() {//left btn click listener
                    @Override
                    public void onBtnClick() {
                        // 取消对话框
                        isUpdateVersionDialogShow = false;
                        dialog.dismiss();
                    }
                },
                new OnBtnClickL() {//right btn click listener
                    @Override
                    public void onBtnClick() {
                        interceptFlag = false;
                        showDownloadDialog();
                    }
                }
        );
    }

    private void downDialog() {
        final DownDialog downDialog = new DownDialog(context);
        downDialog
                .setTitle("正在更新")
                .setOnBtnCancelClick(new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        downDialog.dismiss();
                        interceptFlag = true;
                    }
                }).
                setSaveFileNamel(saveFileName)
                .show();
        mhandler = new DownDialog.DownDialogHandler(downDialog);
        downloadApk();
    }

    /**
     * 下载进度对话框
     */
    private void showDownloadDialog() {
        Builder builder = new Builder(context);
        // builder.setTitle("下载更新");
        final LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.version_update_progress, null);
        mProgress = (ProgressBar) view.findViewById(R.id.versionUpdatePb);
        versionUpdatePrecentTv = (TextView) view.findViewById(R.id.versionUpdatePrecentTv);
        TextView cancelBtn = (TextView) view.findViewById(R.id.cancelBtn);
        builder.setView(view);
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadDialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();
        downloadApk();
    }

    /**
     * 启动线程下载apk
     */
    private void downloadApk() {
        downLoadThread = new Thread(downApkRunnable);
        downLoadThread.start();
    }

    // /**
    // * 安装APK
    // */
    // private void installApk() {
    // Intent intent = new Intent(Intent.ACTION_VIEW);
    // intent.setDataAndType(Uri.fromFile(file),
    // "application/vnd.android.package-archive");
    // startActivity(intent);
    // }

    /**
     * 安装APK
     */
    private void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
        context.startActivity(i);
    }

    public String getLocalversion() {
        return localversion;
    }

    public void setLocalversion(String localversion) {
        this.localversion = localversion;
    }

    /**
     * 截取出url后面的apk的文件名
     *
     * @param url
     * @return
     */
    private String getFilePath(String url) {
        return url.substring(url.lastIndexOf("/"), url.length());
    }

    static class MyHandler extends Handler {
        private final WeakReference<VersionUpdateUtil> outerClass;

        public MyHandler(VersionUpdateUtil innerClass) {
            outerClass = new WeakReference<VersionUpdateUtil>(innerClass);
        }

        @Override
        public void handleMessage(Message msg) {
            VersionUpdateUtil innerClass = outerClass.get();
            switch (msg.what) {
                case DOWN_UPDATE:
                    innerClass.mProgress.setProgress(innerClass.progress);
                    innerClass.versionUpdatePrecentTv.setText(innerClass.progress + "%");
                    break;
                case DOWN_OVER:
                    if (innerClass.downloadDialog != null)
                        innerClass.downloadDialog.dismiss();
                    innerClass.installApk();
                    break;
                default:
                    break;
            }
        }
    }
}